package com.example.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.example.appcontact.A002Login;
import com.example.appcontact.R;
import com.example.model.Contacts;

public class Util {
	public static boolean checkNullString(String name) {
		if (name == null || name.length() < 0 || name.equalsIgnoreCase(""))
			return true;
		return false;
	}

	public static boolean checkNullString(EditText name) {
		String temp = name.getText().toString();
		if (temp == null || temp.length() < 0 || temp.equalsIgnoreCase(""))
			return true;
		return false;
	}

	public static boolean checkEqualString(String name1, String name2) {
		if (name1.equalsIgnoreCase(name2))
			return true;
		return false;
	}

	public static boolean checkDatabase(String path) throws IOException {
		// close();
		File newDb = new File(path);
		return newDb.exists();

	}

	/**
	 * method is used for checking valid email id format.
	 * 
	 * @param email
	 * @return boolean true for valid false for invalid
	 */
	public static boolean isEmailValid(String email) {
		boolean isValid = false;

		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	public static void callPhone(Context context, String number) {
		try {
			if (!Util.checkNullString(number)) {
				Intent callIntent = new Intent(Intent.ACTION_CALL);
				callIntent.setData(Uri.parse("tel:" + number));
				context.startActivity(callIntent);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void sendMail(Context mContext, String mail, Contacts contact) {
		try {
			Intent email = new Intent(Intent.ACTION_SEND);
			email.putExtra(Intent.EXTRA_EMAIL,
					new String[] { "youremail@yahoo.com" });
			email.putExtra(Intent.EXTRA_SUBJECT, "subject");
			email.putExtra(Intent.EXTRA_TEXT, "message");
			email.setType("message/rfc822");
			mContext.startActivity(Intent.createChooser(email,
					"Choose an Email client :"));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static byte[] appendByteArrays(byte[] a, byte[] b) {
		byte[] result = new byte[a.length + b.length];
		System.arraycopy(a, 0, result, 0, a.length);
		System.arraycopy(b, 0, result, a.length, b.length);
		return result;
	}

	/**
	 * Check string is empty or not
	 * 
	 * @param str
	 *            : String to check
	 * @return true if the str is empty or null otherwise return false
	 */

	public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
		Uri uri = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, id);
		InputStream input = ContactsContract.Contacts
				.openContactPhotoInputStream(cr, uri);
		if (input == null) {
			return null;
		}
		return BitmapFactory.decodeStream(input);
	}

	public static String getAndroidId(Context c) {
		return Settings.Secure.getString(c.getContentResolver(),
				Settings.System.ANDROID_ID);
	}

	public static void showDialog(Context context, int title, String msg,
			int btn_name01, int btn_name02, OnClickListener listener01,
			OnClickListener listener02) {
		final AlertDialog a = new AlertDialog.Builder(context)
				.setTitle(context.getResources().getString(title))
				.setMessage(msg)
				.setCancelable(false)
				.setPositiveButton(
						context.getResources().getString(btn_name01),
						listener01)
				.setNegativeButton(
						context.getResources().getString(btn_name02),
						listener02).create();

		a.show();
	}

	public static void showDialog(Context context, int title, int msg,
			int btn_name01, int btn_name02, OnClickListener listener01,
			OnClickListener listener02) {
		final AlertDialog a = new AlertDialog.Builder(context)
				.setTitle(context.getResources().getString(title))
				.setMessage(context.getResources().getString(msg))
				.setCancelable(false)
				.setPositiveButton(
						context.getResources().getString(btn_name01),
						listener01)
				.setNegativeButton(
						context.getResources().getString(btn_name02),
						listener02).create();

		a.show();
	}

	public static void showDialog(Context context, int title, String msg,
			int btn_name01, OnClickListener listener01) {
		final AlertDialog a = new AlertDialog.Builder(context)
				.setTitle(context.getResources().getString(title))
				.setMessage(msg)
				.setCancelable(false)
				.setPositiveButton(
						context.getResources().getString(btn_name01),
						listener01).create();

		a.show();
	}

	public static void showDialog(Context context, int title, int msg, int icon) {
		final AlertDialog a = new AlertDialog.Builder(context)
				.setIcon(context.getResources().getDrawable(icon))
				.setTitle(context.getResources().getString(title))
				.setMessage(context.getResources().getString(msg))
				.setCancelable(false)
				.setNegativeButton("OK", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).create();

		a.show();
	}

	public static void showDialog(Context context, int title, String msg,
			int icon) {
		final AlertDialog a = new AlertDialog.Builder(context)
				.setIcon(context.getResources().getDrawable(icon))
				.setTitle(context.getResources().getString(title))
				.setMessage(msg).setCancelable(false)
				.setNegativeButton("OK", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).create();

		a.show();
	}

	public static final boolean getNetworkStatus(Context context) {
		// システムから接続情報をとってくる
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		/**
		 * MOD 03/18
		 * ----------------------------------------------------------------
		 */
		// モバイル回線（３G）の接続状態を取得 <-
		// Nexus(4.2.2)だとおちてしまう
		NetworkInfo networkInfo = cm
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		State mobile = null;
		if (networkInfo != null) {
			mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
					.getState();
		} else {
			mobile = State.DISCONNECTED;
		}
		/**
		 * MOD 03/18
		 * ----------------------------------------------------------------
		 */
		// wifiの接続状態を取得
		State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();

		// 3Gデータ通信／wifi共に接続状態じゃない場合
		if ((mobile != State.CONNECTED) && (wifi != State.CONNECTED)) {
			// ネットワーク未接続
			return false;
		}

		// ネットワークに接続している
		return true;

	}

	public static int encodeGender(String gender) {
		try {
			if (!TextUtils.isEmpty(gender)) {
				return Integer.parseInt(gender);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return -1;
	}

	
	public static String decodeGenderString(String gender) {
		// gender = "1";
		try {
			if (!TextUtils.isEmpty(gender)) {
				if (gender.equalsIgnoreCase("1"))
					return "Male";
				else if (gender.equalsIgnoreCase("2"))
					return "Female";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return "None";
	}

	public static int[] decodeBirthday(String birthday) {
		// birthday = "05/05/2000";
		int[] temp = null;
		try {
			if (!TextUtils.isEmpty(birthday)) {
				String[] t = birthday.split("/");
				for (int i = 0; i < t.length; i++) {
					Log.e("SON", i + " - " + t[i].toString());
				}
				temp = new int[3];

				temp[0] = Integer.parseInt(t[0]);
				temp[1] = Integer.parseInt(t[1]);
				temp[2] = Integer.parseInt(t[2]);

				for (int i = 0; i < temp.length; i++) {
					Log.e("SON TEMP", i + " - " + temp[i]);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return temp;
	}

	public static String getProperties(Context t, String key) throws Exception {
		InputStream rawResource = t.getResources().openRawResource(
				R.raw.message);
		Properties properties = new Properties();
		properties.load(rawResource);
		return properties.getProperty(key);

	}

	public static void hideSoftKeyboard(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}

	public static Contacts findByEmail(HashMap<String, Contacts> map,
			String email) {
		Contacts result = null;
		result = map.get(email);
		return result;
	}

	public static HashMap<String, Contacts> convertListToMap(List<Contacts> list) {
		HashMap<String, Contacts> hashMap = new HashMap<String, Contacts>();
		if (list != null) {
			for (Contacts i : list) {
				hashMap.put(i.getEmail(), i);
			}
		}
		return hashMap;

	}

	public static List<Contacts> convertMapToList(HashMap<String, Contacts> map) {
		List<Contacts> result = new ArrayList<Contacts>();
		if (map != null) {
			Iterator<String> iter = map.keySet().iterator();
			while (iter.hasNext()) {
				result.add(map.get(iter.next()));
			}
		}
		return result;

	}

	public static void clearToken(Context context) {
		SharedPreferencesDB instance = new SharedPreferencesDB(context);
		instance.setPrefToken("");
	}

	public static void startLogin(Activity context) {
		Util.clearToken(context);
		Intent intent = new Intent();
		intent.setClass(context, A002Login.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		context.startActivity(intent);
		Toast.makeText(context,
				context.getResources().getString(R.string.login_again),
				Toast.LENGTH_SHORT).show();
		context.finish();
	}

	public static String getMyPhoneNumber(Context mContext) {
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getLine1Number();
	}
}
